package com.iotechn.unimall.biz.service.turntable;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.iotechn.unimall.biz.service.coupon.CouponBiz;
import com.iotechn.unimall.biz.service.integral.IntegralBizService;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.util.MoneyUtils;
import com.iotechn.unimall.core.util.wx.WeChatTempleConstants;
import com.iotechn.unimall.core.util.wx.WeChatTempleUtils;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.domain.*;
import com.iotechn.unimall.data.enums.IntegralSonType;
import com.iotechn.unimall.data.enums.SystemStatusType;
import com.iotechn.unimall.data.enums.turntable.TurntablePrizeType;
import com.iotechn.unimall.data.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TurnTableBiz {

    private static final Logger logger = LoggerFactory.getLogger(TurnTableBiz.class);

    @Autowired
    private TurntableMapper turntableMapper;

    @Autowired
    private CacheComponent cacheComponent;

    @Autowired
    private TurntableDetailMapper turntableDetailMapper;

    @Autowired
    private TurntableUserMapper turntableUserMapper;

    @Autowired
    private TurntableUserLogMapper turntableUserLogMapper;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private CouponBiz couponBiz;

    @Autowired
    private IntegralBizService integralBizService;

    @Autowired
    private TurntableRewardLogMapper turntableRewardLogMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取抽奖用户
     * @param userId
     * @return
     */
    public TurntableUserDO makeNewTurntableUser(Long userId){
        Date now = new Date();
        List<TurntableUserDO> turntableUserDOs = turntableUserMapper.selectList(new EntityWrapper<TurntableUserDO>().eq("user_id", userId).eq("status",SystemStatusType.ON.getCode()));
        if(turntableUserDOs == null || turntableUserDOs.size() < 1){
            //完成注册 大转盘抽奖账户
            TurntableUserDO newUser = new TurntableUserDO();
            newUser.setGmtCreate(now);
            newUser.setGmtUpdate(now);
            newUser.setStatus(SystemStatusType.ON.getCode());
            newUser.setUserId(userId);
            newUser.setLuckDrawNum(1);
            turntableUserMapper.insert(newUser);
            return newUser;
        }
        TurntableUserDO turntableUserDO = turntableUserDOs.get(0);
        return turntableUserDO;
    }
    /**
     * 扣减抽奖次数
     * @param userId
     */
    public TurntableUserDO subDrawTimes(Long userId) throws AppServiceException {
        List<TurntableUserDO> turntableUserDOS = turntableUserMapper.selectList(new EntityWrapper<TurntableUserDO>().eq("user_id", userId).eq("status", SystemStatusType.ON.getCode()));
        if(turntableUserDOS == null || turntableUserDOS.size() < 1) {
            throw new AppServiceException("当前用户无抽奖次数",500);
        }
        TurntableUserDO turntableUserDO = turntableUserDOS.get(0);
        Integer luckDrawNum = turntableUserDO.getLuckDrawNum();
        turntableUserDO.setLuckDrawNum(luckDrawNum - 1);
        turntableUserMapper.updateById(turntableUserDO);
        return turntableUserDO;
    }

    /**
     * 分享奖励
     * @param userId
     * @return
     * @throws AppServiceException
     */
    public TurntableUserDO addDrawTimes(Long userId)  throws AppServiceException {
        List<TurntableUserDO> turntableUserDOS = turntableUserMapper.selectList(new EntityWrapper<TurntableUserDO>().eq("user_id", userId).eq("status", SystemStatusType.ON.getCode()));
        if(turntableUserDOS == null || turntableUserDOS.size() < 1) {
            throw new AppServiceException("当前用户无抽奖次数",500);
        }
        TurntableUserDO turntableUserDO = turntableUserDOS.get(0);
        Integer luckDrawNum = turntableUserDO.getLuckDrawNum();
        turntableUserDO.setLuckDrawNum(luckDrawNum + 1);
        turntableUserMapper.updateById(turntableUserDO);
        return turntableUserDO;
    }

    /**
     * 记录
     * @param
     * @return
     */
    public TurntableUserDO insertTurntableUserLog(TurntableUserDO orig,TurntableUserDO curr,Integer type,Integer sonType,Long turntableId,Long turntablePrizeId,String detail){
        Date now = new Date();
        TurntableUserLogDO turntableUserLogDO = new TurntableUserLogDO();
        turntableUserLogDO.setGmtCreate(now);
        turntableUserLogDO.setGmtUpdate(now);
        turntableUserLogDO.setOrigTurnTimes(orig.getLuckDrawNum());
        turntableUserLogDO.setCurrTurnTimes(curr.getLuckDrawNum());
        turntableUserLogDO.setChangeTimes(orig.getLuckDrawNum() - curr.getLuckDrawNum());
        turntableUserLogDO.setSonType(sonType);
        turntableUserLogDO.setType(type);
        turntableUserLogDO.setUserId(curr.getUserId());
        turntableUserLogDO.setTurntableId(turntableId);
        turntableUserLogDO.setTurntablePrizeId(turntablePrizeId);
        turntableUserLogDO.setDetail(detail);
        turntableUserLogMapper.insert(turntableUserLogDO);
        return curr;
    }

    /**
     * 设置奖池
     * @param map
     * @return
     */
    public Map<Integer, TurntableDetailDO> makeJackpot(Map<Integer, TurntableDetailDO> map){
        for(int i=1;i<= 100;i++) {
            map.put(i,null);
        }
        List<TurntableDO> turntableDOS = turntableMapper.selectList(new EntityWrapper<TurntableDO>().eq("status", SystemStatusType.ON.getCode()));
        TurntableDO turntableDO = turntableDOS.get(0);
        List<TurntableDetailDO> turntableDetailDOs = turntableDetailMapper.selectList(new EntityWrapper<TurntableDetailDO>().eq("turntable_id", turntableDO.getId()));
        int index = 0;
        for (TurntableDetailDO turntableDetailDO: turntableDetailDOs
        ) {
            BigDecimal winRate = turntableDetailDO.getWinRate();
            double winRateD = winRate.doubleValue();
            Double winRateBase = MoneyUtils.mul(winRateD, 100D);
            winRateBase = MoneyUtils.div(winRateBase,1D,0);
            int winRateBaseInt = winRateBase.intValue() + index;
            int winRateBaseIntCheck=  0;
            //根据比例分配中奖因子
            while (index < winRateBaseInt){
                index++;
                map.put(index,turntableDetailDO);
            }
        }

        return map;
    }

    // 1.谢谢惠顾
    // 2.优惠券
    // 将优惠券写到已领取
    // 3.现金
    //调用微信  支付现金
    // 4.积分
    //奖励积分 1.增加用户积分 2.写用户积分流水

    /**
     * 分奖
     * @param turntableDetailDO
     * @return
     * @throws AppServiceException
     */
    public TurntableDetailDO sendRewards(Long userId,TurntableDetailDO turntableDetailDO) throws AppServiceException {
        //谢谢惠顾
        if(turntableDetailDO.getPrizeType().intValue() == TurntablePrizeType.NOPRIZE.getCode()){
            return null;
        }
        //奖励商品
        if(turntableDetailDO.getPrizeType().intValue() == TurntablePrizeType.GOODPRIZE.getCode()){
            return null;
        }
        //奖励优惠券
        if(turntableDetailDO.getPrizeType().intValue() == TurntablePrizeType.COUPONPRIZE.getCode()){
            //奖品  优惠券id
            Long prizeId = turntableDetailDO.getPrizeId();
            CouponDO couponDO = couponMapper.selectById(prizeId);
            rewardCoupon(userId,turntableDetailDO,couponDO);
            return turntableDetailDO;
        }
        //奖励积分
        if(turntableDetailDO.getPrizeType().intValue() == TurntablePrizeType.INTEGRALPRIZE.getCode()){
            rewaredIntegral(userId,turntableDetailDO);
            return turntableDetailDO;
        }
        //奖励现金
        if(turntableDetailDO.getPrizeType().intValue() == TurntablePrizeType.CASHPRIZE.getCode()){
            return null;
        }
        throw new AppServiceException("抽奖异常",500);
    }


    /**
     * 奖励优惠券
     * @param turntableDetailDO
     * @return
     */
    public TurntableDetailDO rewardCoupon(Long userId,TurntableDetailDO turntableDetailDO,CouponDO couponDO) throws AppServiceException {
        couponBiz.userReceiveCoupon(userId,couponDO);
        return turntableDetailDO;
    }

    /**
     * 大转盘奖励积分
     * @param turntableDetailDO
     * @return
     */
    public TurntableDetailDO rewaredIntegral(Long userId,TurntableDetailDO turntableDetailDO){
        integralBizService.addIntegral(userId,turntableDetailDO.getPrizeNum(),IntegralSonType.TURNTABLEREWARD.getCode(),"大转盘奖励"+turntableDetailDO.getPrizeNum()+"积分",turntableDetailDO.getId());
        return turntableDetailDO;
    }

    /**
     * 添加奖励记录
     * @param userId
     * @param turntableId
     * @param turntablePrizeId
     * @param prizeNum
     */
    public void insertTurntableRewardLog(Long userId,Long turntableId,Long turntablePrizeId,Integer prizeNum){
        Date now = new Date();
        TurntableRewardLogDO turntableRewardLog = new TurntableRewardLogDO();
        turntableRewardLog.setGmtCreate(now);
        turntableRewardLog.setGmtUpdate(now);
        turntableRewardLog.setStatus(SystemStatusType.ON.getCode());
        turntableRewardLog.setUserId(userId);
        turntableRewardLog.setTurntableId(turntableId);
        turntableRewardLog.setTurntablePrizeId(turntablePrizeId);
        turntableRewardLog.setPrizeNum(prizeNum);
        turntableRewardLog.setRewardTime(now);
        turntableRewardLogMapper.insert(turntableRewardLog);
    }


    /**
     * 优惠券提示
     * @param userId
     * @param couponDO
     */
    public void turnTabGiveCoupon(Long userId,CouponDO couponDO){
        UserDO userDO = userMapper.selectById(userId);
        String token ="";
        if(cacheComponent.hasKey(WeChatTempleUtils.getCacheToken(userId))){
            token = cacheComponent.getRaw(WeChatTempleUtils.getCacheToken(userId));
        }else{
            Map<String, Object> tokenMap = WeChatTempleUtils.getaccessToken();
            token = (String) tokenMap.get(WeChatTempleUtils.TOKENKEY);
            Integer second = (Integer) tokenMap.get(WeChatTempleUtils.EXPIRETIMEKEY);
            cacheComponent.putObj(WeChatTempleUtils.getCacheToken(userId),token,second);
        }
        Map<String,String> datas =new HashMap<>();
        datas.put("thing3","大转盘");
        datas.put("thing7","您获得一张"+couponDO.getTitle()+"，请及时使用~");
        Map<String,String> sendData =new HashMap<>();
        sendData.put(WeChatTempleUtils.MK_TOUSER,userDO.getOpenId());
        sendData.put(WeChatTempleUtils.MK_TEMPLATE, WeChatTempleConstants.ACTIVITYMSG);
        sendData.put(WeChatTempleUtils.MK_PAGE,"");
        sendData.put(WeChatTempleUtils.MK_MINIPROGRAM,WeChatTempleUtils.pattern);
        Map<String, Object> newOrderTmp = WeChatTempleUtils.getNewOrderTmp(datas, sendData);
        try {
            String s = WeChatTempleUtils.sendTempleMsg(newOrderTmp, token);
            logger.info("模板消息返回"+ s);
            logger.info("抽奖获取优惠券");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 抽奖积分
     * @param userId
     * @param integral
     */
    public void turnTabGiveIntegral(Long userId,Integer integral){
        UserDO userDO = userMapper.selectById(userId);
        String token ="";
        if(cacheComponent.hasKey(WeChatTempleUtils.getCacheToken(userId))){
            token = cacheComponent.getRaw(WeChatTempleUtils.getCacheToken(userId));
        }else{
            Map<String, Object> tokenMap = WeChatTempleUtils.getaccessToken();
            token = (String) tokenMap.get(WeChatTempleUtils.TOKENKEY);
            Integer second = (Integer) tokenMap.get(WeChatTempleUtils.EXPIRETIMEKEY);
            cacheComponent.putObj(WeChatTempleUtils.getCacheToken(userId),token,second);
        }
        Map<String,String> datas =new HashMap<>();
        datas.put("thing3","大转盘");
        datas.put("thing7","您抽奖获得"+ integral+"积分，请及时使用~");
        Map<String,String> sendData =new HashMap<>();
        sendData.put(WeChatTempleUtils.MK_TOUSER,userDO.getOpenId());
        sendData.put(WeChatTempleUtils.MK_TEMPLATE, WeChatTempleConstants.ACTIVITYMSG);
        sendData.put(WeChatTempleUtils.MK_PAGE,"");
        sendData.put(WeChatTempleUtils.MK_MINIPROGRAM,WeChatTempleUtils.pattern);
        Map<String, Object> newOrderTmp = WeChatTempleUtils.getNewOrderTmp(datas, sendData);
        try {
            String s = WeChatTempleUtils.sendTempleMsg(newOrderTmp, token);
            logger.info("模板消息返回"+ s);
            logger.info("抽奖获取积分");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
